package com.dailyblue.java.project.smbms.goods.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.commons.util.JsonResult;
import com.dailyblue.java.commons.util.ResultTool;
import com.dailyblue.java.project.smbms.goods.bean.Goods;
import com.dailyblue.java.project.smbms.goods.feign.ProviderFeign;
import com.dailyblue.java.project.smbms.goods.feign.StockFeign;
import com.dailyblue.java.project.smbms.goods.mapper.GoodsMapper;
import com.dailyblue.java.project.smbms.goods.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Resource
    private StockFeign stockFeign;
    @Resource
    private ProviderFeign providerFeign;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // 1. 将所有的商品ID存放到Redis的zset中
    ZSetOperations<String, String> zset;
    // 2. 将每个商品单独存放到Redis,KEY是商品编号，Value是商品信息
    ValueOperations<String, String> value;


    //@Cacheable(cacheNames = "findGoods", key = "#page")
    public JsonResult findGoods(int page) {
        zset = stringRedisTemplate.opsForZSet();
        value = stringRedisTemplate.opsForValue();
        log.info("开始获取第{}页的商品信息", page);
        int start = (page - 1) * 5;
        int end = page * 5;
        Set<String> set = zset.range("GOODS_PAGE", start, end - 1);
        log.info("获取到的数据是:{}", set);
        List<Goods> list;
        PageInfo pageInfo;
        // 当前页数不存在时的情况
        if (set == null || set.size() == 0) {
            log.info("没有获取到第{}页的数据", page);
            PageHelper.startPage(page, 5);
            list = list();
            log.info("从数据库中获取到的数据：{}", list);
            for (Goods goods : list) {
                // 调用包装的方法把供应商和库存
                goods = packing(goods);
                // 将数据库中的ID存放到了Redis中
                zset.add("GOODS_PAGE", goods.getId() + "", goods.getId());
                // 将商品ID存放到Redis
                value.set("GOODS_" + goods.getId(), JSONArray.toJSONString(goods));
            }
            pageInfo = new PageInfo(list);
            // 将商品总数和总页数保存到redis中
            value.set("GOODS_TOTAL", pageInfo.getTotal() + "");
            value.set("GOODS_PAGES", pageInfo.getPages() + "");
            return ResultTool.success(pageInfo);
        }
        log.info("Redis获取到了数据");
        list = new ArrayList<>();
        // 当前页数存在时的情况
        for (String s : set) {
            log.info("-------------------------------------------------------------------");
            // 获取到商品ID
            int goodsId = Integer.parseInt(s);
            String g = value.get("GOODS_" + goodsId);
            log.info("goodsId:{},g:{}", goodsId, g);
            Goods goods;
            if (g == null) {
                // 通过商品ID获取到商品详细信息
                goods = getById(goodsId);
                value.set("GOODS_" + goodsId, JSONArray.toJSONString(goods));
            } else {
                goods = JSONArray.parseObject(g, Goods.class);
            }
            goods = packing(goods);
            list.add(goods);
        }
        pageInfo = new PageInfo(list);
        int total = Integer.parseInt(value.get("GOODS_TOTAL"));
        int pages = Integer.parseInt(value.get("GOODS_PAGES"));
        pageInfo.setTotal(total);
        pageInfo.setPages(pages);
        return ResultTool.success(pageInfo);
    }

    @Cacheable(cacheNames = "find", key = "#goodsName+'.'+#proId")
    public JsonResult find(String goodsName, int proId) {
        goodsName = "%" + goodsName + "%";
        PageHelper.startPage(1, 5);
        List<Goods> list = getBaseMapper().find(goodsName, proId);
        log.info("service获取的list：{}", list);
        for (Goods g : list) {
            packing(g);
        }
        return ResultTool.success(new PageInfo<>(list));
    }

    @Override
    public JsonResult find(int id) {
        ValueOperations value = stringRedisTemplate.opsForValue();
        Object v = value.get("GOODS_" + id);
        Goods goods;
        if (v != null) {
            goods = JSONArray.parseObject(v.toString(), Goods.class);
        } else {
            goods = getById(id);
            value.set("GOODS_" + id, JSONArray.toJSONString(goods));
        }
        return ResultTool.success(goods);
    }

    private Goods packing(Goods goods) {
        JsonResult stock = stockFeign.find(goods.getId());
        JsonResult provider = providerFeign.find(goods.getProviderId());
        //log.info("开始获取{}的库存，获取供应商ID:{}的信息", goods.getId(), goods.getProviderId());
        //log.info("stock:{},provider:{}", stock, provider);
        goods.setStock(stock);
        goods.setProvider(provider);
        //log.info("goods:{}", goods);
        return goods;
    }
}
